import sys
import os

from http import HTTPStatus

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, ".."))
sys.path.append(os.path.join(thisDir, "..", "ps"))
sys.path.append(os.path.join(thisDir, "..", "..", "common"))

import SessionManager
import EJOConst

from EJOHandlerBase import EJOHandlerBase

import logging
logger = logging.getLogger(__name__)

class EJOGetDebt(EJOHandlerBase):
    def _doHandle(self):
        logger.debug(f"Handled by: {__name__}")

        startDate = self._convertToDateObj(self._getParamValue("from"))
        endDate = self._convertToDateObj(self._getParamValue("to"))
        if startDate == None or endDate == None or endDate < startDate:
            return True, HTTPStatus.BAD_REQUEST, "Bad date param"

        session = self._getParamValue("session")
        fid = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_FAMILY_ID, session)

        sql = "select " + \
             "debt.Start as start, debt.End as end, " + \
             "debt.Amount as amount, debt.Balance as balance, debt.Note as note" + \
             " from " + \
             "debt" + \
             " where FID=" + str(fid) + " and " + \
             "(debt.Start <= '" + self._getParamValue("to") + "' and debt.End >= '" + self._getParamValue("from") + "')" + \
             " order by debt.Start asc"

        db = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_DB)
        result = []
        for row in db.Execute(sql):
            startDateResult = row[0].split()[0]
            endDateResult = row[1].split()[0]
            amount = row[2]
            balance = row[3]
            note = row[4]
            result.append([startDateResult, endDateResult, amount, balance, note])

        return True, HTTPStatus.OK, str(result)
